package com.mvc.demo.controller;

import com.mvc.demo.bean.AddGroup;
import com.mvc.demo.bean.ResponseInfo;
import com.mvc.demo.bean.User;
import com.mvc.demo.bean.ValidatorPojo;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * @author H
 * @date 2023/1/7
 */
@RestController
@RequestMapping("validator")
public class TestValidatorController {

    @RequestMapping(value = "/test", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseInfo<String> test(@Validated(AddGroup.class) ValidatorPojo validatorPojo) {

        return ResponseInfo.success("success");
    }

    @RequestMapping(value = "/test1", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseInfo<String> test1(@RequestBody @Validated(AddGroup.class) ValidatorPojo  validatorPojo) {
        return ResponseInfo.success("success");
    }

    // /**
    //  * 调用控制器前先执行这个方法, 一旦加入了该方法，此类中其它的所有自动校验都失效
    //  *
    //  * @param binder
    //  */
    // @InitBinder
    // public void initBinder(WebDataBinder binder) {
    //     // 绑定验证器
    //     binder.setValidator(new UserValidator());
    //     // 定义日期参数格式，参数不再需要注解@DateTimeFormat,boolean参数表示是否允许为空
    //     binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
    // }

    @RequestMapping(value = "/test12", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseInfo<String> test2(@Valid User user, Errors errors) throws Exception {
        // 判断是否存在错误
        if (errors.hasErrors()) {
            // 获取全部错误
            List<ObjectError> allErrors = errors.getAllErrors();
            for (ObjectError error : allErrors) {
                // 判断是否字段错误
                if (error instanceof FieldError) {
                    // 字段错误
                    FieldError fieldError = (FieldError) error;
                    throw new Exception(fieldError.getDefaultMessage());
                } else {
                    // 对象错误
                    throw new Exception(error.getDefaultMessage());
                }
            }
        }

        return ResponseInfo.success("success");
    }

}
